package com.queen.rxjavaretrofitdemo.activity;

import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

import com.queen.rxjavaretrofitdemo.R;

import java.io.IOException;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;
import okhttp3.ResponseBody;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;

/**
 * 作者： andli
 * 时间： 2017/11/24 08:42
 * 描述： Retrofit HelloWorld
 */
public class MainActivity extends AppCompatActivity {

    @Bind(R.id.apibtn)
    Button apibtn;

    @Bind(R.id.formatbtn)
    Button formatbtn;

    @Bind(R.id.responseinfo_txt)
    TextView responseinfoTxt;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        ButterKnife.bind(this);
    }

    @OnClick({R.id.apibtn, R.id.formatbtn})
    public void onViewClicked(View view) {
        switch (view.getId()) {

            // 请求接口
            case R.id.apibtn:

//                getAPI1(); // GET请求：豆瓣电影API

                getAPI2(); // GET请求：Bmob列表

                break;

            // 格式化输出
            case R.id.formatbtn:
                String jsonstr = responseinfoTxt.getText().toString();
                responseinfoTxt.setText(stringToJSON(jsonstr));
                break;
        }
    }


    /**
     * GET请求：豆瓣电影API
     */
    private void getAPI1() {

        /**
         * 1.创建Retrofit实例
         */
        String baseUrl = "https://api.douban.com/v2/movie/"; // 注意必须以/号结尾哦

        Retrofit retrofit = new Retrofit.Builder()
                .baseUrl(baseUrl)
                .addConverterFactory(GsonConverterFactory.create())
                .build();

        /**
         * 2.调用接口（通过代理对象）
         */
        APIService apiService = retrofit.create(APIService.class);

        Call<ResponseBody> call = apiService.getTopMovie(0, 4);

        call.enqueue(new Callback<ResponseBody>() {

            @Override
            public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {

                // 通过ResponseBody获取json字符串
                try {
                    String jsonstr = response.body().string();
                    Log.i("andli", jsonstr);
                    responseinfoTxt.setText(jsonstr);

                } catch (IOException e) {
                    e.printStackTrace();
                }

            }

            @Override
            public void onFailure(Call<ResponseBody> call, Throwable t) {
                responseinfoTxt.setText(t.getMessage());
            }

        });

    }

    /**
     * GET请求：Bmob列表
     */
    private void getAPI2() {

        /**
         * 1.创建Retrofit实例
         */
        String baseUrl = "https://api.bmob.cn/"; // 注意必须以/号结尾哦

        Retrofit retrofit = new Retrofit.Builder()
                .baseUrl(baseUrl)
                .addConverterFactory(GsonConverterFactory.create())
                .build();

        /**
         * 2.调用接口（通过代理对象）
         */
        APIService apiService = retrofit.create(APIService.class);

        String id = "417456fd012b34129486d57bc1e1e8a2";
        String key = "45c2a063d6a7cbc9bbdd219b03afe159";

        Call<ResponseBody> call = apiService.getBmobList(id, key, 5);

        call.enqueue(new Callback<ResponseBody>() {

            @Override
            public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {

                // 通过ResponseBody获取json字符串
                try {
                    String jsonstr = response.body().string();
                    Log.i("andli", jsonstr);
                    responseinfoTxt.setText(jsonstr);

                } catch (IOException e) {
                    e.printStackTrace();
                }

            }

            @Override
            public void onFailure(Call<ResponseBody> call, Throwable t) {
                responseinfoTxt.setText(t.getMessage());
            }

        });

    }

    /**
     * 格式化JSON输出
     *
     * @param strJson
     * @return
     */
    public static String stringToJSON(String strJson) {
        // 计数tab的个数
        int tabNum = 0;
        StringBuffer jsonFormat = new StringBuffer();
        int length = strJson.length();

        char last = 0;
        for (int i = 0; i < length; i++) {
            char c = strJson.charAt(i);
            if (c == '{') {
                tabNum++;
                jsonFormat.append(c + "\n");
                jsonFormat.append(getSpaceOrTab(tabNum));
            } else if (c == '}') {
                tabNum--;
                jsonFormat.append("\n");
                jsonFormat.append(getSpaceOrTab(tabNum));
                jsonFormat.append(c);
            } else if (c == ',') {
                jsonFormat.append(c + "\n");
                jsonFormat.append(getSpaceOrTab(tabNum));
            } else if (c == ':') {
                jsonFormat.append(c + " ");
            } else if (c == '[') {
                tabNum++;
                char next = strJson.charAt(i + 1);
                if (next == ']') {
                    jsonFormat.append(c);
                } else {
                    jsonFormat.append(c + "\n");
                    jsonFormat.append(getSpaceOrTab(tabNum));
                }
            } else if (c == ']') {
                tabNum--;
                if (last == '[') {
                    jsonFormat.append(c);
                } else {
                    jsonFormat.append("\n" + getSpaceOrTab(tabNum) + c);
                }
            } else {
                jsonFormat.append(c);
            }
            last = c;
        }
        return jsonFormat.toString();
    }

    private static String getSpaceOrTab(int tabNum) {
        StringBuffer sbTab = new StringBuffer();
        for (int i = 0; i < tabNum; i++) {
            sbTab.append('\t');
        }
        return sbTab.toString();
    }


}
